<template>
	<view class="Register_content">
		<view class="register_box">
			<view class="register_title">
				<image src="../../static/image/back_icon.png" @tap="back" :style="i18n.xiaobaistyle"></image>
				<text>{{i18n.register_title}}</text>
			</view>

			<view class="input_content" :style="i18n.xiaobaibg1"><input type="number" v-model="phone" :placeholder="i18n.input_placeholder1"
				 placeholder-class="placeHolder" /></view>
			<view class="Verification_Code">
				<view class="vcode_input" :style="i18n.xiaobaiyzmbg">
					<!-- <text class="yqmtext">{{i18n.yqmtext}}</text> -->
					<input type="text" v-model="vcode" :placeholder="i18n.input_placeholder2" placeholder-class="placeHolder" /></view>
				<text @tap="send_vcode" v-if="sendVode">{{i18n.send_vcode}}</text>
				<text v-else>{{vtext}}</text>
			</view>

			<view class="child_account">
				<view class="input_content child_account_input" :style="i18n.xiaobaibg3"><input type="text" v-model="accountName"
					 :placeholder="i18n.xiaobaibg3placeholder" placeholder-class="placeHolder" /></view>
				<image src="../../static/image/question_icon.png" class="question_icon"></image>
			</view>

			<text class="actual_account_text" :style="i18n.sjzhmstyle">{{i18n.sjzhm}}：oexchainofficial.{{accountName}}</text>

			<view class="xiaobai_password password_style" :style="i18n.xiaobaibg4">
				<input :type="eye?'text':'password'" v-model="password" :placeholder="i18n.xiaobaibg4placeholder" placeholder-class="placeHolder" />
				<image :src="eye?'../../static/image/openeye_green.png':'../../static/image/closeeye_green.png'" @tap="chageEye(1)"
				 class="eyes"></image>
			</view>
			<view class=" xiaobai_confirm password_style" :style="i18n.xiaobaibg5">
				<input :type="eye2?'text':'password'" v-model="password2" :placeholder="i18n.xiaobaibgplaceholder"
				 placeholder-class="placeHolder" />
				<image :src="eye2?'../../static/image/openeye_green.png':'../../static/image/closeeye_green.png'" @tap="chageEye(2)"
				 class="eyes"></image>
			</view>
			<view class="input_content yqmcontent" :style="i18n.xiaobaibg6">
				<text class="yqmtext">{{i18n.yqmtext}}</text>
				<input type="text" v-model="fathercode" :placeholder="i18n.xiaobaibg6placeholder" placeholder-class="placeHolder" /></view>

			<view class="agreement" @tap="agree_ruls">
				<image :src="agree ? '../../static/image/xieyi_select.png' : '../../static/image/xieyi_icon.png' "></image>
				<view class="agreement_text">
					{{i18n.agreement_text1}}
					<text @tap="agreementClick">{{i18n.agreement_text2}} </text>
				</view>
			</view>

		<!-- 	<button type="default" style="border:none"> -->
				<image :src="changeColor?i18n.changeColorbg1:i18n.changeColorbg2" class="register_btn" @tap="register"></image>
			<!-- </button> -->
			<view class="login_entry" @tap="login">{{i18n.zjdl}}？</view>
		</view>
		<moveble-view :movebleView="movebleViewStyle" :angle="a" @verification="changeVerification"></moveble-view>
	</view>
</template>

<script>
	import {
		ethers
	} from 'ethers';
	import CryptoJS from 'crypto-js';
	import Files from '../../common/files.js'
	import EthCrypto from 'eth-crypto';
	import checkInput from '../../common/checkInput.js'
	import movebleView from '../../components/moveble-view/movable-view.vue'
	export default {
		data() {
			const privateKey = "";
		
			return {
				agree: false, //init agree
				phone: "",
				vcode: "",
				accountName: "",
				password: "",
				password2: "",
				sendVode: true,
				vtext: this._i18n.locale == 'zh_CN' ? '发送验证码' : 'Send verification code',
				Wallet: "", //钱包
				publicKey: "",
				changeColor: false,
				eye: false,
				eye2: false,
				fathercode: "",
				apptoken: "",
				rcode: "",
				jwd: "",
				//验证框显示
				allSliderStyleText: "display:none",
				rotationAngleText: "",
				a: "",
				movebleViewStyle: "display:none",
				verificationData: "",
				run: false
			}
		},
		components: {
			movebleView
		},
		computed: {
			changeData() {
				const {
					phone,
					vcode,
					accountName,
					password,
					password2,
					agree,
					fathercode
				} = this
				return {
					phone,
					vcode,
					accountName,
					password,
					password2,
					agree,
					fathercode
				}
			},
			i18n() {
				return this.$t('user')
			}
		},
		watch: {
			changeData: {
				handler: function(newval, oldval) {
					this.phone = newval.phone;
					this.vcode = newval.vcode;
					this.accountName = newval.accountName;
					this.password = newval.password;
					this.password2 = newval.password2;
					this.agree = newval.agree;
					this.fathercode = newval.fathercode;
					if (this.phone != "" && this.vcode != "" && this.accountName != "" && this.password != "" && this.password2 != "" &&
						this.agree && this.fathercode != "") {
						this.changeColor = true
					} else {
						this.changeColor = false
					}
				},
				deep: true
			}
		},
		onLoad() {
			this.getAppToken();
			this.getRecod();
			var _this = this
			uni.request({
				url: this.$API.appServeApi + this.$API.geticode + '?i18n_language=' + uni.getStorageSync('system_info'),
				method: 'GET',
				success(res) {
					if (res.statusCode == 200) {
						if (res.data.data) {
							_this.fathercode = res.data.data.icode
						}
					}
				},
				fail() {
					_this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? 'apptoken 请求失败' : 'Apptoken request failed')
				}
			})
			// plus.geolocation.getCurrentPosition(function(p) { //获取用户设备位置
			// 	var dz = p.coords.latitude + ''
			// 	var dz2 = p.coords.longitude + ""
			// 	let latitude = dz.split(".")[0]
			// 	let longitude = dz2.split(".")[0]
			// 	_this.jwd = latitude + ':' + longitude
			// 	console.log(_this.jwd)
			// }, function(e) {})
			uni.getLocation({
			    type: 'wgs84',
			    success: function (res) {
			        console.log('当前位置的经度：' + res.longitude);
			        console.log('当前位置的纬度：' + res.latitude);
												var dz =  res.latitude + ''
												var dz2 = res.longitude+ ""
												let latitude = dz.split(".")[0]
												let longitude = dz2.split(".")[0]
												_this.jwd = latitude + ':' + longitude
											
			    }
			});
		},
		onShow() {
			var _this = this
			_this.changeVerification()
			if (_this.verificationData) {
				_this.register()
			}
		},
		methods: {
			getAppToken() {
				const localApptoken = uni.getStorageSync('apptoken');
				const _this = this;
				if (!localApptoken) {
					uni.request({
						url: this.$API.appServeApi + this.$API.apptoken + '?i18n_language=' + uni.getStorageSync('system_info'),
						method: 'GET',
						success(apptokenInfo) {
							if (apptokenInfo.data.code == 200) {
								_this.apptoken = apptokenInfo.data.data
								uni.setStorageSync('apptoken', apptokenInfo.data.data)
							} else {
								_this.$CommonJS.showToast(apptokenInfo.data.message)
							}
						},
						fail() {
							_this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? 'apptoken 请求失败' : 'Apptoken request failed')
						}
					})
				} else {
					_this.apptoken = localApptoken;
				}
			},
			getRecod() {
				const _this = this;
				uni.request({
					url: this.$API.appServeApi + this.$API.rcode + '?i18n_language=' + uni.getStorageSync('system_info'),
					success(recodeInfo) {
						if (recodeInfo.data.code == 200) {
							_this.rcode = recodeInfo.data.data
						} else {
							_this.$CommonJS.showToast(recodeInfo.data.message)
						}
					},
					fail(err) {
						_this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? 'recode 请求失败' : 'Recode request failed')
					}
				})
			},
			chageEye(n) {
				if (n == 1) {
					this.eye = !this.eye;
				} else {
					this.eye2 = !this.eye2;
				}
			},
			back() {
				this.$CommonJS.navigateBack()
			},
			login() {
				this.$CommonJS.navigateTo('../login/login')
			},
			agree_ruls() {
				//同意协议
				this.agree = !this.agree;
			},
			agreementClick() {
				this.$CommonJS.navigateTo('../agreementClick/agreementClick')
			},
			send_vcode() {
				//发送验证码
				const _this = this;
				if (!this.phone) {
					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '请输入手机号' : 'Please enter your mobile phone number');
					return;
				}
				if (!this.$CommonJS.PhoneValidate(this.phone)) {
					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '手机号不正确' : 'Incorrect mobile phone number');
					return;
				}
				uni.showLoading({
				})
				const url = this.$API.appServeApi + this.$API.phoneValidate + '?i18n_language=' + uni.getStorageSync('system_info') + "&mobile=" + this.phone + "&rtype=0" + "&codetype=0";
				this.$CommonJS.request(url, "POST").then(res => {
					if (res.data.code == 200) {
						_this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '验证码已发送' : 'Verification code sent')
						_this.getTime();
						uni.hideLoading()
					} else {
						console.log(res.data.message)
						_this.$CommonJS.showToast(res.data.message)
						uni.hideLoading()
					}
				}).catch(error => {
					//console.log(error)
					_this.$CommonJS.showToast(error.message)
					uni.hideLoading()
				})
			},
			getTime() {
				//倒计时
				var _this = this;
				var num = 60;
				var timer = setInterval(function() {
					if (num <= 0) {
						clearInterval(timer);
						_this.vtext = "";
						_this.sendVode = true;
						return;
					}
					_this.vtext = (_this._i18n.locale == 'zh_CN' ? '重新发送' + num + 's' : 'Resend' + num + 's');
					num--;
				}, 1000)
				_this.sendVode = !_this.sendVode;
			},
			async register() {
				const _this = this;
				//注册
				const phoneResult = checkInput.emptyValidate(this.phone, _this._i18n.locale == 'zh_CN' ? '手机号' :
					'cell-phone number');
				if (!phoneResult.result) {
					this.$CommonJS.showToast(phoneResult.message);
					return;
				}
				if (!(/^1[3456789]\d{9}$/.test(this.phone))) {
					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '手机号码有误，请重填' :
						'Wrong mobile number, please fill in again');
					return;
				}
				if (!this.vcode) {
					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '请输入验证码' : 'Please enter the verification code');
					return;
				}
				if (!this.accountName) {
					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '请输入子账户名' : 'Please enter sub account name');
					return;
				}
				if (!this.$CommonJS.accountValidate(this.accountName, 0)) {
					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '账号名请输入3-15数字字母组合' :
						'Please input 3-15 letters for account number');
					return;
				}
				//账户名
				if (!this.password) {
					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '请输入密码' : 'Please input a password');
					return;
				}
				if (!this.$CommonJS.passwordValidate(this.password)) {
					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '密码请输入8-16位数字字母组合' :
						'Please input 8-16 digit alphanumeric combination for password');
					return;
				}
				if (!this.password2) {
					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '请输入确认密码' : 'Please enter the confirmation password');
					return;
				}
				if (this.password !== this.password2) {
					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '两次输入的密码不一致' : 'The two passwords are not the same');
					return;
				}
				if (!this.agree) {
					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '未同意用户协议' : 'User agreement not agreed');
					return;
				}
				if (this.fathercode == "") {
					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '邀请码不能为空' : 'Invitation code cannot be empty');
					return;
				}
				if (this.apptoken == "") {
					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? 'apptoken 不能为空' : 'Apptoken cannot be empty');
					return;
				}
				if (this.rcode == "") {
					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? 'recode 不能为空' : 'Recode cannot be empty');
					return;
				}
				
				if (_this.run == true) {
					_this.movebleViewStyle = "display:none"
					uni.showLoading({
						// title:"正在注册"
						title: _this._i18n.locale == 'zh_CN' ? '正在注册' : 'Registering',
					})
					const identity = EthCrypto.createIdentity();
					const Wallet = await new ethers.Wallet(identity.privateKey) //创建一个新的随机钱包
					this.Wallet = {
						privateKey: Wallet.privateKey,
						publicKey: Wallet.publicKey,
					}
					this.publicKey = Wallet.publicKey;
					var key = CryptoJS.enc.Utf8.parse("QWERTYHUJKOLL34C");
					var srcs = CryptoJS.enc.Utf8.parse(_this.accountName);
					var encrypted = CryptoJS.AES.encrypt(srcs, key, {
						mode: CryptoJS.mode.ECB,
						padding: CryptoJS.pad.Pkcs7
					});
					_this.rcode = encrypted.toString()
					//请求接口，传参子账号注册信息
					const url = this.$API.appServeApi + this.$API.registerXiaoBai + '?i18n_language=' + uni.getStorageSync('system_info');
					console.log(_this.jwd)
					const data = {
						account: this.accountName,
						mobile: this.phone,
						valcode: this.vcode,
						publickey: this.publicKey,
						isfather: 0,
						apptoken: this.apptoken,
						rcode: this.rcode,
						fathercode: this.fathercode,
						jwd: _this.jwd
					}
					uni.request({
						url: url,
						method: "POST",
						header: {
							'content-type': 'application/x-www-form-urlencoded' //自定义请求头信息
						},
						data: data,
						success(res) {
							//console.log(res)
							if (res.data.code == 200) {
								//对称加密
								var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(_this.Wallet), _this.password).toString();
								const xiaobai = _this.$API.xiaobai + _this.accountName + '.txt';
								//	写入文件
								Files.fileWriter(ciphertext, xiaobai).then(txt => {
									if (txt.status == 200) {
										uni.hideLoading();
										uni.showToast({
											// title:"注册成功",
											title: _this._i18n.locale == 'zh_CN' ? '注册成功' : 'login was successful',
											success() {
												_this.$CommonJS.navigateTo('../login/login')
											}
										})
									}
								}).catch(err => {
									_this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? 'keystore 保存失败' : 'Keystore save failed')
								})
							} else {
								uni.hideLoading();
								_this.$CommonJS.showToast(res.data.message);
							}
						},
						fail(error) {
							uni.hideLoading();
							_this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '网络异常请重新注册' :
								'Network exception, please register again')
							_this.run = false
						}
					})
				} else { //显示滑块验证框
					_this.movebleViewStyle = "display:block"
				}
			},
			changeVerification(data) { //子组件传递过来的值
				var _this = this
				if (data) {
					_this.movebleViewStyle = data
					_this.run = true
					_this.register()
				}
			},
		}
	}
</script>

<style lang="stylus">
	@import "../../static/stylus/register/xiaobai_user.stylus"
</style>